<template>
	<view class="page quotation-add">
		<!-- 基本信息 -->
		<view class="title">基本信息</view>
		<view class="panel">
			<u-form :model="form" ref="uForm" :label-width="210" :error-type="['toast']">
				<u-form-item v-for="(v, k) in fields" :key="k" :label="v.name" :prop="v.fieldName" :required="v.isNull == 1">
					<u-input v-model="form[v.fieldName]" :type="formTypes[v.formType]" :placeholder="v.inputTips" :disabled="v.isDisabled == 1" @click="handlerSelect(v, k)" />
				</u-form-item>
			</u-form>
		</view>

		<!-- 审核信息 -->
		<examine-info type="11"></examine-info>

		<!-- 按钮 -->
		<footer-bar>
			<u-button type="primary" @click="save(1)">提交审核</u-button>
			<u-button type="warning" @click="save(2)">保存草稿</u-button>
			<u-button type="error" @click="save(3)">取消</u-button>
		</footer-bar>

		<!-- 日历组件 -->
		<u-calendar v-model="calendar.status" :mode="calendar.mode" :safe-area-inset-bottom="true" max-date="9999-12-31" @change="calendarChange"></u-calendar>
		<!-- 选择客户、商机、上传附件 -->
		<u-popup v-model="popup.status" closeable :mode="popup.mode" :length="popup.height" :safe-area-inset-bottom="true" border-radius="10">
			<component :is="popup.widget" :data="popup.data" @selected="popSelected"></component>
		</u-popup>
	</view>
</template>

<script>
import oRow from '@/components/oveui-layout/o-row/o-row.vue';
import oCol from '@/components/oveui-layout/o-col/o-col.vue';
// 客户列表
import listCustomer from '../common/listCustomer';
// 商机列表
import listBusiness from '../common/listBusiness';
// 审核信息
import examineInfo from '../common/examineInfo';
// 上传文件
import uploadFile from '../common/uploadFile';
// 操作按钮
import footerBar from '../common/footerBar';
import { guid } from '@/utils';
export default {
	components: { oRow, oCol, listCustomer, listBusiness, examineInfo, footerBar, uploadFile },
	data: () => ({
		// 当前id
		id: 0,
		// 字段
		fields: [],
		// 表单
		form: {},
		rules: {},
		// 表单类型对照表
		formTypes: {
			date: 'select',
			text: 'text',
			customer: 'select',
			business: 'select',
			file: 'select',
			textarea: 'textarea',
		},
		// 当前操作select的字段名称
		curField: '',
		// 当前操作select的索引
		curIndex: -1,
		// 日历组件相关字段
		calendar: {
			status: false,
			mode: 'date',
		},
		// 弹窗信息
		popup: {
			status: false,
			mode: 'bottom',
			height: '600px',
			widget: '',
			data: [],
		},
	}),
	methods: {
		// 获取字段
		async getFields() {
			let data = {
				label: 11,
			};

			let BASE_URL = this.$env[this.envName].BASE_URL;

			// 编辑的时候传入参数
			this.id > 0 && (data.id = this.id);

			let res = await this.$api.customer.common.fields(data);
			if (res.code === 200) {
				let list = res.data || [];
				this.fields = list;

				list.forEach((v, k) => {
					// 设置表单
					if (this.id > 0) {
						// 编辑回显
						if (v.fieldName === 'customer_id') {
							this.form[v.fieldName] = v.value[0].customerName;
							this.fields[k].valueKey = v.value[0].customerId;
						} else if (v.fieldName === 'business_id') {
							this.form[v.fieldName] = '';
						} else if (v.formType === 'file') {
							this.form[v.fieldName] = `已上传${v.value.length}个文件`;
							this.fields[k].batchId = v.value[0].batchId;
							v.list = [];
							v.value.forEach((file) => {
								v.list.push({
									url: BASE_URL + file.filePath,
								});
							});
						} else {
							this.form[v.fieldName] = v.value || '';
						}
					} else {
						this.form[v.fieldName] = v.value;
					}

					// 设置校验规则
					if (v.isNull == 1 && (!v.value || v.value.length == 0)) {
						this.rules[v.fieldName] = {
							required: true,
							message: v.inputTips || v.name + '不能为空',
							trigger: ['blur', 'change'],
						};
					}
				});
			}
		},
		// 处理select数据
		handlerSelect(row, index) {
			this.curField = row.fieldName;
			this.curIndex = index;

			// 日期
			if (row.formType === 'date') {
				this.calendar.status = true;
			}
			// 客户
			if (row.formType === 'customer') {
				this.popup.widget = 'listCustomer';
				this.popup.status = true;
			}
			// 商机
			if (row.formType === 'business') {
				// 如果没有选择客户
				if (!this.form.customer_id) {
					uni.showToast({
						icon: 'none',
						title: '请选择客户',
					});
					return;
				}
				this.popup.data = {
					customerId: this.fields.find((v) => v.fieldName === 'customer_id').valueKey,
				};
				this.popup.widget = 'listBusiness';
				this.popup.status = true;
			}
			// 文件
			if (row.formType === 'file') {
				this.fields[this.curIndex].batchId = row.batchId ? row.batchId : guid();
				this.popup.widget = 'uploadFile';
				this.popup.data = {
					list: this.fields[this.curIndex].list || [],
					batchId: row.batchId,
				};
				this.popup.status = true;
			}
		},
		// 日历回调
		calendarChange(data) {
			this.form[this.curField] = data.result;
		},
		// pop弹窗回调
		async popSelected(type, data) {
			// 客户
			if (type === 'customer') {
				this.form.customer_id = data.customerId;
				this.popup.data = data;

				// 设置表单值
				this.form[this.curField] = data.customerName;
				this.fields[this.curIndex].valueKey = data.customerId;
			}
			// 商机
			if (type === 'business') {
				// 设置表单值
				this.form[this.curField] = data.businessName;
				this.fields[this.curIndex].valueKey = data.business_id;
			}
			// 文件
			if (type === 'file') {
				// 设置表单值
				this.form[this.curField] = '已上传' + data.length + '个文件';
				this.fields[this.curIndex].list = data;
				this.popup.data = {
					list: data,
					batchId: this.fields[this.curIndex].batchId,
				};
			}

			this.popup.status = false;
		},
		// 保存数据
		save(type) {
			if ([1, 2].includes(type)) {
				// 提交审核
				let data = {
					field: [],
					businessInfo: {},
					entity: { ...this.form },
				};
				// 保存草稿
				if (type === 2) {
					data.entity.checkStatus = 5;
				}
				// 如果是编辑带上id
				if (this.id) {
					data.entity.preSalesId = this.id;
					data.entity.batchId = guid();
				}
				// 处理存在field中的下啦选择的值
				this.fields.forEach((v) => {
					if (v.valueKey != null) {
						data.entity[v.fieldName] = v.valueKey;
					}
					if (v.formType === 'file') {
						v.value = v.batchId;
						delete v.batchId;
						data.field.push(v);
					}
				});

				if ('设备清单' in data.entity) {
					delete data.entity['设备清单'];
				}

				// console.log(data);
				// return;

				// 校验
				this.$refs.uForm.validate(async (valid) => {
					if (!valid) {
						return;
					}

					let res = await this.$api.customer.preSales.save(data);
					if (res.code === 200) {
						uni.showToast({
							icon: 'none',
							title: '操作成功',
						});
						// 返回上一页
						uni.navigateBack();
					}
				});
			}
			if (type == 3) {
				// 取消，返回上一页
				// 返回列表
				uni.navigateBack();
			}
		},
	},
	computed: {
		envName() {
			return process.env.NODE_ENV || 'development';
		},
	},
	watch: {},

	// 周期函数--监听页面加载
	onLoad(options) {
		this.id = options.id ? options.id : 0;
		this.getFields();
	},
	// 周期函数--监听页面初次渲染完成
	onReady() {
		console.log(this.rules);
		this.$refs.uForm.setRules(this.rules);
	},
	// 周期函数--监听页面显示
	onShow() {
		if (this.id) {
			uni.setNavigationBarTitle({
				title: '编辑设备清单',
			});
		}
	},
	// 周期函数--监听页面隐藏
	onHide() {},
	// 周期函数--监听页面卸载
	onUnload() {},
	// 页面处理函数--监听用户下拉动作
	onPullDownRefresh() {},
	// 页面处理函数--监听用户上拉触底
	onReachBottom() {},
	// 页面处理函数--监听页面滚动
	/* onPageScroll(event) {}, */
	// 页面处理函数--用户点击右上角分享
	/* onShareAppMessage(options) {}, */
};
</script>

<style lang="scss" scoped>
.page {
	background: #efefef;
}
.mb20 {
	margin-bottom: 20px;
}
.title {
	padding: 15px 15px 10px;
}
.panel {
	background: #fff;
	padding: 15px;
}

.u-select /deep/ .u-drawer,
.u-drawer {
	z-index: 998 !important;
}
.u-field {
	padding: 10px 14px;
	color: #303133;

	.u-field-inner {
		display: flex;
	}

	.u-label {
		width: 65px;
	}
}
</style>
